package com.camel.base.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.camel.base.feign.AutoCallServiceService;
import com.camel.base.model.CtiTask;
import com.camel.base.model.ZsQuestion;
import com.camel.base.service.CtiTaskService;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.entity.IParams;
import com.camel.core.entity.Result;
import com.camel.core.exceptions.CustomException;
import com.camel.core.service.BaseCommonService;
import com.camel.core.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author camel
 */
@RestController
@RequestMapping("task")
public class CtiTaskController extends BaseCommonController<CtiTask> {

    @Autowired
    private CtiTaskService<CtiTask> service;

    @Autowired
    private AutoCallServiceService autoCallServiceService;

    @Override
    public Result save(@RequestBody CtiTask entity) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        entity.setTaskid(formatter.format(new Date()));
        JSONObject jsonObject = entity.toJSONObject();
        Result save = autoCallServiceService.save(jsonObject);
        if(save.isSuccess()) {
            Result ssave = super.save(entity);
            if(ssave.isSuccess()) {
                return ResultUtil.success();
            }
        }
        return ResultUtil.error(500, getMouduleName() + "创建失败");
    }


    @GetMapping("/refresh")
    public Result refresh(String taskid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("taskid", taskid);
        Result result = autoCallServiceService.list(jsonObject);
        JSONArray jsonArray = result.JSONArray();
        if(!CollectionUtils.isEmpty(jsonArray)) {
            CtiTask ctiTask = CtiTask.fromJSON((JSONObject) jsonArray.get(0));
            service.saveOrUpdate(ctiTask, new UpdateWrapper<CtiTask>().eq("taskid", ctiTask.getTaskid()));
        }
        return ResultUtil.success();
    }

    @GetMapping("/sync")
    public Result sync() {
        Result result = autoCallServiceService.list(new JSONObject());
        Object data = result.getData();
        if(!ObjectUtils.isEmpty(data)) {
            JSONArray array = result.JSONArray();
            for (Object o : array) {
                JSONObject object = (JSONObject) o;
                CtiTask ctiTask = CtiTask.fromJSON(object);
                service.saveOrUpdate(ctiTask, new UpdateWrapper<CtiTask>().eq("taskid", ctiTask.getTaskid()));
            }
        }
        return ResultUtil.success("操作成功");
    }

    @Override
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Serializable id) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("taskid", id);
        Result del = autoCallServiceService.del(jsonObject);
        if(del.isSuccess()) {
            return super.delete(id);
        }else {
            return ResultUtil.deleteError(getMouduleName());
        }
    }

    @Override
    public Result update(@RequestBody CtiTask entity) {
        JSONObject params = new JSONObject();
        Assert.notNull(entity.getTaskid(), "任务ID不能为空！");
        params.put("taskid", entity.getTaskid());

        if(!ObjectUtils.isEmpty(entity.getMaxConcurrentNum())) {
            params.put("max_concurrent_num", entity.getMaxConcurrentNum());
        }

        if(!ObjectUtils.isEmpty(entity.getCalledNumber())) {
            params.put("pstnNumber", entity.getCalledNumber());
        }

        if(!ObjectUtils.isEmpty(entity.getXintf())) {
            params.put("xintf", entity.getXintf());
            entity.setXintf(entity.getIsValid().toString());
        }

        if(StringUtils.isEmpty(entity.getHitRate())) {
            entity.setHitRate("0");
        }
        if(StringUtils.isEmpty(entity.getAcwTime())) {
            entity.setAcwTime("40");
        }
        if(StringUtils.isEmpty(entity.getRedialTimes())) {
            entity.setRedialTimes("3");
        }
        if(StringUtils.isEmpty(entity.getMinRedialInterval())) {
            entity.setMinRedialInterval("5");
        }
        if(StringUtils.isEmpty(entity.getMaxRingTime())) {
            entity.setMaxRingTime("45");
        }


        params.put("hitRate", entity.getHitRate());
        params.put("acwTime", entity.getAcwTime());
        params.put("redialTimes", entity.getRedialTimes());
        params.put("minRedialInterval", entity.getMinRedialInterval());
        params.put("maxRingTime", entity.getMaxRingTime());


        Result update = autoCallServiceService.update(params);
        if(update.isSuccess()) {
            return super.update(entity);
        }
        return ResultUtil.error(500, "外呼任务参数修改失败");
    }

    @Override
    public boolean deleteAble(Serializable id) {
        CtiTask byId = service.getById(id);
        if (ObjectUtils.isEmpty(byId)) {
            throw new CustomException("删除失败: " + getMouduleName() + "不存在");
        }
        return true;
    }

    @Override
    public BaseCommonService<CtiTask> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "外呼队列";
    }
}
